<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class Post extends Model
{

    protected $table='posts';
    protected $fillable=['title','content','user_id'];

    //关联用户
    public function user()
    {
        return $this->belongsTo('App\Models\User','user_id','id')->select('id','username');
    }
    //评论模型
    public function comments()
    {
        return $this->hasMany('App\Models\Comment','post_id','id')->orderBy('created_at','desc');
    }
    //赞 关联用户对文章的赞
    public function zan($user_id)
    {
        return $this->hasOne('App\Models\Zan')->where('user_id',$user_id);
    }
    //all赞
    public function zans()
    {
        return $this->hasMany('App\Models\Zan');
    }

    //属于作者的文章
    public function scopeAuthorBy(Builder $query,$user_id)
    {
        return $query->where('user_id',$user_id);
    }
    //文章和专题的关联
    public function postTopic()
    {
        return $this->hasMany('App\Models\PostTopic','post_id','id');
    }
    //不属于摸个专题的文章
    public function scopeTopicNotBy(Builder $query,$topic_id)
    {

        return $query->doesntHave('postTopic','and',function ($q) use($topic_id){
            return $q->where('topic_id',$topic_id);
        });
    }
    


}
